package com.joker.aigc.ai.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;

/**
 * 语音识别工具类 将 音频文件进行语音识别
 *
 * @author feixiang.li
 * @since 2025-09-28
 */
public class SpeechRecognitionUtils {

    private static final String API_URL = "https://openai.qiniu.com/v1/voice/asr";
    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 通过URL进行语音识别（与原curl命令相同的方式）
     *
     * @param audioUrl 音频文件URL
     * @return 识别后的文字信息
     */
    public static String recognizeSpeechByUrl(String audioUrl, String apiKey) {
        try {
            // 根据文件扩展名确定格式
            String format = getAudioFormat(audioUrl);

            // 构建请求体
            String requestBody = String.format(
                    "{\"model\": \"asr\", \"audio\": {\"format\": \"%s\", \"url\": \"%s\"}}",
                    format, audioUrl
            );

            // 创建HTTP请求
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(API_URL))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .POST(BodyPublishers.ofString(requestBody))
                    .build();

            // 发送请求并获取响应
            HttpClient client = HttpClient.newHttpClient();
            HttpResponse<String> response = client.send(
                    request, HttpResponse.BodyHandlers.ofString());

            System.out.println(response.body());

            // 处理响应
            if (response.statusCode() == 200) {
                JsonNode root = mapper.readTree(response.body());
                return root.get("data").get("result").get("text").asText();
            } else {
                throw new RuntimeException("API请求失败: " + response.statusCode() + " - " + response.body());
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据文件URL确定音频格式
     */
    private static String getAudioFormat(String audioUrl) {
        if (audioUrl.toLowerCase().endsWith(".wav")) {
            return "wav";
        } else if (audioUrl.toLowerCase().endsWith(".webm")) {
            return "webm";
        } else if (audioUrl.toLowerCase().endsWith(".mp3")) {
            return "mp3";
        } else if (audioUrl.toLowerCase().endsWith(".m4a")) {
            return "m4a";
        } else {
            // 默认使用WAV格式
            return "wav";
        }
    }

    public static void main(String[] args) {
        System.out.println("开始识别...");
        long startTime = System.currentTimeMillis();
        // 基本使用
        String mp3Url = "https://fakerlove.oss-cn-beijing.aliyuncs.com/recorded_audio.wav";
        String result = SpeechRecognitionUtils.recognizeSpeechByUrl(mp3Url, "sk-05bc0a43150ec29cfe555de2ffcb22a116ff5ee5e7a");
        long endTime = System.currentTimeMillis();
        System.out.println("识别完成，耗时: " + (endTime - startTime) + "ms");
        System.out.println("识别结果: " + result);
    }


    // 请求体数据结构
    static class RecognitionRequest {
        public String model;
        public AudioData audio;

        public RecognitionRequest(String model, AudioData audio) {
            this.model = model;
            this.audio = audio;
        }
    }

    static class AudioData {
        public String format;
        public String data;

        public AudioData(String format, String data) {
            this.format = format;
            this.data = data;
        }
    }
}